<?php

namespace App\Admin\Controllers;

use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;

use Encore\Admin\Facades\Admin;

use App\Services\DeviceInfoService;
use App\Models\HostInfo;
use App\Models\DeviceInfo;
use App\Models\DeviceType;
use App\Models\AreaInfo;

use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;

use Log;

class OneKeyController extends AdminController
{
    public function index(Content $content)
    {

        $content->title('一键控制');
        $content->row('<br/>');
        $content->row(function(Row $row) {
            
            $row->column(1, '<a id="on_btn" class=" btn btn-big btn-success"><i class="fa fa-plug"></i>&nbsp;&nbsp;一键开馆</a>');
            
            $row->column(1, '<a id="off_btn" class=" btn btn-big btn-danger"><i class="fa fa-power-off"></i>&nbsp;&nbsp;一键闭馆</a>');
            $row->column(1, '');
            $row->column(9, '');
        });

        $this->script = <<<EOT
    //一键开馆
    $('#on_btn').unbind('click').click(function() {
        swal({
            title: "确认打开全部的电源吗？",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确认",
            showLoaderOnConfirm: true,
            cancelButtonText: "取消",
            preConfirm: function() {

                $.ajax({
                    method: 'get',
                    url: '/api/getDevices',
                    success: function (data) {
                        // console.log(data);
                        var o = eval("(" + data + ")");  // 转换为json对象
                        // console.log(o.data);
                        var _swal;
                        var i = 0;
                        var t = setInterval(function() {
                            var _id = o.data[i].id;
                            var _name = o.data[i].name;
                            var _cmd = o.data[i].cmd;
                            $.ajax({
                                method: 'get',
                                url: '/api/sentCmd?id=' + _id + '&flag=12&cmd=' + _cmd,
                                success: function (data) {
                                    // console.log(data);
                                    var o = eval("(" + data + ")");  // 转换为json对象
                                    // console.log(o.code);
                                    
                                    if(o.code == '200') {
                                        $.admin.toastr.success('打开' + _name + '打开' + _name + '的电源成功！<br/>请勿关闭浏览器，正在打开下一个', '', {positionClass:"toast-top-center"});
                                        // _swal = swal({
                                        //       title: '打开' + _name + '的电源成功！<br/>请勿关闭浏览器，正在打开下一个',
                                        //       type: "success",
                                        // });
                                    } else{
                                        $.admin.toastr.error('打开' + _name + '的电源失败！<br/>请勿关闭浏览器，正在打开下一个', '', {positionClass:"toast-top-center"});
                                        // _swal = swal({
                                        //       title: '打开' + _name + '的电源失败！<br/>请勿关闭浏览器，正在打开下一个',
                                        //       type: "error",
                                        // });
                                    }
                                    

                                }
                            }); 
                            i += 1;
                            if(i > o.data.length - 1) {
                                clearInterval(t);
                                $.ajax({
                                    method: 'get',
                                    url: '/api/updateHost',
                                    success: function (data) {
                                        console.log(data);
                                    }
                                });
                                $.pjax.reload('#pjax-container');
                                var _swal1 = swal({
                                      title: '电源已全部开启！',
                                      type: "success",
                                });
                            }
                        }, 3000);
                    }
                });
            }
        });
    });

    // 一键闭馆
    $('#off_btn').unbind('click').click(function() {
        swal({
            title: "确认关闭全部的电源吗？",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确认",
            showLoaderOnConfirm: true,
            cancelButtonText: "取消",
            preConfirm: function() {
                $.ajax({
                    method: 'get',
                    url: '/api/getHosts',
                    success: function (data) {
                        // console.log(data);
                        var o = eval("(" + data + ")");  // 转换为json对象
                        console.log(o.data);
                        swal('正在发送关机命令，请不要关闭浏览器！', '', 'success');
                        o.data.forEach(function (item, index) {
                            console.log(item);
                            if(item.sys == 'win') {
                                $.ajax({
                                    url: 'http://' + item.ip + ':8001',
                                    type: 'POST',
                                    dataType: 'jsonp',  //数据格式为jsonp
                                    jsonp: 'callback',  //函数变量名
                                    jsonpCallback: 'list',
                                    success:function(data){  //成功的回调函数
                                        console.log(data);
                                    },
                                    error: function (e) {
                                        console.log(e)
                                    }
                                });
                            } else {
                                $.ajax({
                                    method: 'get',
                                    url: '/api/hostShutdown?id=' + item.id + '&ip=' + item.ip + '&cmd=' + item.cmd,
                                    success: function (data) {
                                        console.log(data);
                                    }
                                });
                            }
                             
                        });

                        var i = 0;
                        var t = setInterval(function() {
                            var _id = o.data[i].id;
                            var _ip = o.data[i].ip;
                            var _name = o.data[i].name;
                            $.ajax({
                                method: 'get',
                                url: '/api/checkHost?ip=' + _ip + '&id=' + _id,
                                success: function (data) {
                                    console.log(data);
                                    if(data == 0 ) {
                                        $.admin.toastr.success( _name + "电脑关机成功!", '', {positionClass:"toast-top-center"});
                                    } else {
                                        $.admin.toastr.error(_name + "电脑关机失败!", '', {positionClass:"toast-top-center"});
                                    }
                                    $.pjax.reload('#pjax-container');
                                }
                            });

                            i += 1;
                            if(i > o.data.length - 1) {
                                clearInterval(t);
                                var _swal1 = swal({
                                      title: '全部主机关闭，正在发送关闭电源命令！',
                                      type: "success",
                                });

                                $.ajax({
                                    method: 'get',
                                    url: '/api/getDevices',
                                    success: function (data) {
                                        // console.log(data);
                                        var o = eval("(" + data + ")");  // 转换为json对象
                                        console.log(o.data);

                                        var ii = 0;
                                        var tt = setInterval(function() {
                                            var _id = o.data[ii].id;
                                            var _name = o.data[ii].name;
                                            var _cmd = o.data[ii].cmd;
                                            $.ajax({
                                                method: 'get',
                                                url: '/api/sentCmd?id=' + _id + '&flag=11&cmd=' + _cmd,
                                                success: function (data) {
                                                    // console.log(data);
                                                    var o = eval("(" + data + ")");  // 转换为json对象
                                                    // console.log(o.code);
                                                    
                                                    if(o.code == '200') {
                                                        $.admin.toastr.success('关闭' + _name + '的电源成功！', '', {positionClass:"toast-top-center"});
                                                    }else{
                                                        $.admin.toastr.error('关闭' + _name + '的电源失败！', '', {positionClass:"toast-top-center"});
                                                    }
                                                    $.pjax.reload('#pjax-container');
                                                }
                                            }); 
                                            ii += 1;
                                            if(ii > o.data.length - 1){
                                                clearInterval(tt);
                                                var _swal1 = swal({
                                                      title: '电源已全部关闭！',
                                                      type: "success",
                                                });
                                            }
                                        },3000);
                                    }
                                });
                            }
                        }, 8000);
                    }
                });
            }
        });
    });
EOT;
        Admin::script($this->script);
        $content->row('<br/>');
        $content->row('<h3>主机列表</h3>');
        $content->row($this->hostgrid());
        $content->row('<br/>');
        $content->row('<h3>电源列表</h3>');
        $content->row($this->grid());
        return $content;
    }

    protected function hostgrid()
    {
        $grid = new Grid(new HostInfo);

        $grid->disablePagination();
        $grid->disableCreateButton();
        $grid->disableFilter();
        $grid->disableExport();
        $grid->disableRowSelector();
        $grid->disableActions();
        $grid->disableColumnSelector();

        $grid->column('id', __('Id'));
        $grid->column('name', __('名称'));
        $grid->column('desc', __('描述'));
        $grid->column('ip', __('IP地址'));
        $grid->column('sys', __('操作系统'));
      
        $grid->column('status', __('状态'))->using(['0' => '<span style="color:red">已关机</span>', '1' => '<span style="color:green">运行中</span>'], '未知');
        $grid->column(' ', __('开关操作'))->display(function () {
            if ($this['status'] == '1') {
                return "<a class='btn btn-danger btn-sm host-row-off' data-id='{$this}'>关闭</a>";
            } else {
                return "";
            }
        });
        $this->script = <<<EOT
        // row 关机
        $('.host-row-off').unbind('click').click(function() {
            console.log($(this).data('id'));
            var _id = $(this).data('id').id;
            var _sys = $(this).data('id').sys;
            var _name = $(this).data('id').name;
            var _ip = $(this).data('id').ip;
            var _cmd = $(this).data('id').cmd;
            swal({
                title: "确认关机" + _name + "吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    if(_sys == "ubuntu"){
                        $.ajax({
                            method: 'get',
                            url: '/api/hostShutdown?id=' + _id + '&ip=' + _ip + '&cmd=' + _cmd,
                            success: function (data) {
                                console.log(data);
                                var _swal = swal({
                                  title: "正在等待关机，请不要关闭浏览器!",
                                  type: "warning",
                                });
                                setTimeout(function() {
                                    $.ajax({
                                        method: 'get',
                                        url: '/api/checkHost?ip=' + _ip + '&id=' + _id,
                                        success: function (data) {
                                            console.log(data);
                                            if(data == 0 ) {
                                                swal({
                                                  title: _name + "电脑关机成功!",
                                                  type: "success",
                                                });
                                            } else {
                                                swal({
                                                  title: _name + "电脑关机失败!",
                                                  type: "error",
                                                });
                                            }
                                            $.pjax.reload('#pjax-container');
                                        }
                                    });
                                }, 8000);
                            }
                        });
                    } else {
                        $.ajax({
                            url: 'http://' + _ip + ':8001',
                            type: 'POST',
                            dataType: 'jsonp',  //数据格式为jsonp
                            jsonp: 'callback',  //函数变量名
                            jsonpCallback: 'list',
                            success:function(data){  //成功的回调函数
                                console.log(data);
                                var _swal = swal({
                                  title: "正在等待关机，请不要关闭浏览器!",
                                  type: "warning",
                                });
                                setTimeout(function() {
                                    $.ajax({
                                        method: 'get',
                                        url: '/api/checkHost?ip=' + _ip + '&id=' + _id,
                                        success: function (data) {
                                            console.log(data);
                                            if(data == 0 ) {
                                                swal({
                                                  title: _name + "电脑关机成功!",
                                                  type: "success",
                                                });
                                            } else {
                                                swal({
                                                  title: _name + "电脑关机失败!",
                                                  type: "error",
                                                });
                                            }
                                            $.pjax.reload('#pjax-container');
                                        }
                                    });
                                }, 8000);
                            },
                            error: function (e) {
                                console.log(e)
                            }
                        });
                    }
                }
            });
        });
EOT;

        Admin::script($this->script);        
        return $grid;
    }
     /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {

        $grid = new Grid(new DeviceInfo);
        
        $grid->disablePagination();
        $grid->disableCreateButton();
        $grid->disableFilter();
        $grid->disableExport();
        $grid->disableRowSelector();
        $grid->disableActions();
        $grid->disableColumnSelector();

        $grid->column('id', __('Id'));
        $grid->column('code', __('设备编码'));
        $grid->column('name', __('设备名称'));
        $grid->column('type', __('设备类型'))->display(function ($type) {
            return DeviceType::where(['id'=>$type])->pluck('name')[0];
        });
        $grid->column('area', __('区域'))->display(function ($area) {
            return AreaInfo::where(['id'=>$area])->pluck('name')[0];
        });
        $grid->column('desc', __('描述'));
        $grid->column('cmd', __('指令'));
        $grid->column('status', __('状态'))->using(['11' => '<span style="color:red">关</span>', '12' => '<span style="color:green">开</span>'], '未知');

        $grid->column('enable', __('状态'))->using(['0' => '无效', '1' => '有效'], '未知');

        // $grid->column('', __('开关操作'))->display(function () {
        //     return "<a class='btn btn-success btn-sm grid-row-on' data-id='{$this}'>开</a>    <a class='btn btn-danger btn-sm grid-row-off' data-id='{$this}'>关</a>";
        // });

        $grid->column(' ', __('开关操作'))->display(function () {
            if ($this['status'] == '11') {
                return "<a class='btn btn-success btn-sm grid-row-on' data-id='{$this}'>开启</a>";
            } else {
                return "<a class='btn btn-danger btn-sm grid-row-off' data-id='{$this}'>关闭</a>";
            }
        });

        $this->script = <<<EOT

        //open all
        $('.openall-posts').unbind('click').click(function() {
            swal({
                title: "确认打开全部的电源吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {

                    var row_on = $(".grid-row-on");
                    console.log(row_on.length);
                    var i = 0;
                    var t = setInterval(function(){
                        // console.log($(row_on[i]).data('id'));
                        var _id = $(row_on[i]).data('id').id;
                        var _name = $(row_on[i]).data('id').name;
                        var _cmd = $(row_on[i]).data('id').cmd;
                        $.ajax({
                            method: 'get',
                            url: '/api/sentCmd?id=' + _id + '&flag=12&cmd=' + _cmd,
                            success: function (data) {
                                // console.log(data);
                                var o = eval("(" + data + ")");  // 转换为json对象
                                // console.log(o.code);
                                
                                if(o.code == '200') {
                                    $.admin.toastr.success('打开' + _name + '的电源成功！', '', {positionClass:"toast-top-center"});
                                }else{
                                    $.admin.toastr.error('打开' + _name + '的电源失败！', '', {positionClass:"toast-top-center"});
                                }
                                $.pjax.reload('#pjax-container');

                            }
                        }); 
                        i += 1;
                        if(i > row_on.length - 1){
                            clearInterval(t);
                            $.pjax.reload('#pjax-container');
                        }
                    },5000);
                }
            });
        });


        $('.grid-row-on').unbind('click').click(function() {
            console.log($(this).data('id'));
            // console.log($(this).data('id').name);
            // console.log($(this).data('id').cmd);
            var _id = $(this).data('id').id;
            var _name = $(this).data('id').name;
            var _cmd = $(this).data('id').cmd;
            swal({
                title: "确认打开" + _name + "的电源吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.ajax({
                        method: 'get',
                        url: '/api/sentCmd?id=' + _id + '&flag=12&cmd=' + _cmd,
                        success: function (data) {
                            console.log(data);
                            var o = eval("(" + data + ")");  // 转换为json对象
                            console.log(o.code);
                            
                            if(o.code == '200') {
                                swal('打开' + _name + '的电源成功！', '', 'success');
                            }else{
                                swal('打开' + _name + '的电源失败！', '', 'error');
                            }
                            $.pjax.reload('#pjax-container');

                        }
                    });
                }
            });
        });

        $('.grid-row-off').unbind('click').click(function() {
            // console.log($(this).data('id'));
            // console.log($(this).data('id').name);
            // console.log($(this).data('id').cmd);
            var _id = $(this).data('id').id;
            var _name = $(this).data('id').name;
            var _cmd = $(this).data('id').cmd;
            swal({
                title: "确认关闭" + _name + "的电源吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.ajax({
                        method: 'get',
                        url: '/api/sentCmd?id=' + _id + '&flag=11&cmd=' + _cmd,
                        success: function (data) {
                            console.log(data);
                            var o = eval("(" + data + ")");  // 转换为json对象
                            console.log(o.code);
                            
                            if(o.code == '200') {
                                swal('关闭' + _name + '的电源成功！', '', 'success');
                            }else{
                                swal('关闭' + _name + '的电源失败！', '', 'error');
                            }
                            $.pjax.reload('#pjax-container');
                        }
                    });
                }
            });
        });
EOT;

        Admin::script($this->script);

        return $grid;
    }
}
